using Microsoft.AspNetCore.Authorization;

namespace WebApplication1.Auth;

public class MustRoleAdminHandle
    :IAuthorizationHandler
{
    private readonly IHttpContextAccessor _httpContextAccessor;

    public MustRoleAdminHandle(IHttpContextAccessor httpContextAccessor)
    {
        _httpContextAccessor = httpContextAccessor;
    }

    public Task HandleAsync(AuthorizationHandlerContext context)
    {
        // 做验证判断，如果验证通过，则 context.Successed();
        // 可以看形参 context 里的各种属性
        // 比如：
        //var requirement = context.Requirements.FirstOrDefault();
        //context.Succeed(requirement);        // 这样设置后就返回 200
        
        // 或者设置 Fail()
        // context.Fail();

        var requirement = context.Requirements.FirstOrDefault();
        
        // 获取用户信息
        var userId = context.User.Identity?.Name ?? context.User.FindFirst("sub")?.Value;

        // 获取请求的接口路径
        var path = _httpContextAccessor.HttpContext?.Request?.Path.Value;
        
        if (userId != null && path != null)
        {
                context.Succeed(requirement);
        }
        else
        {
            context.Fail();
        }
        return Task.CompletedTask; 
    }
}